package com.istar.framework.dao.implement;

import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.SessionFactory;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;

import com.istar.framework.dao.interfaces.ICommonDao;

@Repository
public abstract class CommonDaoImpl<T> extends HibernateDaoSupport implements
		ICommonDao<T> {

	private Class<T> entityClass;

	@SuppressWarnings("unchecked")
	public CommonDaoImpl() {
		entityClass = (Class<T>) ((ParameterizedType) getClass()
				.getGenericSuperclass()).getActualTypeArguments()[0];
	}

	@Autowired
	private void setSession(SessionFactory sessionFactory) {
		this.setSessionFactory(sessionFactory);
	}

	public boolean insert(T entity) {
		boolean flag = false;
		try {
			getHibernateTemplate().save(entity);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	public boolean update(T entity) {
		boolean flag = false;
		try {
			getHibernateTemplate().update(entity);
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	public boolean delete(int id) {
		boolean flag = false;
		try {
			T entity = get(id);
			if (entity != null) {
				getHibernateTemplate().delete(entity);
			}
			flag = true;
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		return flag;
	}

	public List<T> listAll() {
		return getHibernateTemplate().loadAll(entityClass);
	}

	public T get(int id) {
		T entity = null;
		try {
			entity = getHibernateTemplate().get(entityClass, id);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return entity;
	}

	@SuppressWarnings("unchecked")
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria) {
		return (List<T>) getHibernateTemplate()
				.findByCriteria(detachedCriteria);
	}

	@SuppressWarnings("unchecked")
	public List<T> getListByCriteria(DetachedCriteria detachedCriteria,
			int offset, int size) {
		return (List<T>) getHibernateTemplate().findByCriteria(
				detachedCriteria, offset, size);
	}

}
